#!/bin/bash
# This script creates a self-signed certificate for testing purposes.
# Usage: ./createCert.sh <domain>
# 检查参数
if [ "$#" -lt 1 ]; then
    echo "Usage: $0 <domain> [password]"
    exit 1
fi

DOMAIN=$1
PASSWORD=$2
# 获取当前脚本所在的目录
SCRIPT_DIR=$(cd "$(dirname "$0")" && pwd)

# 定义文件名
CLIENT_CONF_FILE="$SCRIPT_DIR/openssl-client.cnf"
SERVER_CONF_FILE="$SCRIPT_DIR/openssl-server.cnf"
OPENSSL_CONF_FILE="$SCRIPT_DIR/openssl.cnf"

# 生成openssl-client.cnf
echo "[ req ]
default_bits       = 2048
distinguished_name = req_distinguished_name
prompt             = no
[ req_distinguished_name ]
C  = CN
ST = Shanghai
L  = Shanghai
O  = MyOrg
OU = Client
CN = myclient" > "$CLIENT_CONF_FILE"

# 生成openssl-server.cnf
echo "[ req ]
default_bits       = 2048
distinguished_name = req_distinguished_name
req_extensions     = req_ext
prompt             = no

[ req_distinguished_name ]
C  = CN
ST = Shanghai
L  = Shanghai
O  = MyOrg
OU = Server
CN = $DOMAIN

[ req_ext ]
subjectAltName = @alt_names

[ alt_names ]
IP.1 = $DOMAIN" > "$SERVER_CONF_FILE"

echo "[ req ]
prompt = no
distinguished_name = req_distinguished_name

[ req_distinguished_name ]
C  = CN
ST = Shanghai
L  = Shanghai
O  = MyOrg
CN = MyRootCA" > "$OPENSSL_CONF_FILE"

# 创建证书目录
mkdir -p "$SCRIPT_DIR/cert"
# 生成 CA 私钥
openssl genrsa -out "$SCRIPT_DIR/cert/ca.key" 4096
# 生成自签名的 CA 证书（有效期365天）
openssl req -new -x509 -days 365 -key $SCRIPT_DIR/cert/ca.key -out $SCRIPT_DIR/cert/ca.crt -config $OPENSSL_CONF_FILE
# 生成服务器私钥和证书请求：
openssl genrsa -out $SCRIPT_DIR/cert/server.key 2048
openssl req -new -key $SCRIPT_DIR/cert/server.key -out $SCRIPT_DIR/cert/server.csr -config $SCRIPT_DIR/openssl-server.cnf
# 使用 CA 签发服务器证书：
openssl x509 -req -days 365 -in $SCRIPT_DIR/cert/server.csr -CA $SCRIPT_DIR/cert/ca.crt -CAkey $SCRIPT_DIR/cert/ca.key -CAcreateserial -out $SCRIPT_DIR/cert/server.crt -extfile $SCRIPT_DIR/openssl-server.cnf -extensions req_ext
# 生成客户端私钥和证书请求：

if [ -n "$PASSWORD" ]; then
    # 带密码生成
    openssl genrsa -des3 -passout pass:"$PASSWORD" -out $SCRIPT_DIR/cert/client.key 2048
else
    # 不带密码生成
    openssl genrsa -out $SCRIPT_DIR/cert/client.key 2048
fi

if [ -n "$PASSWORD" ]; then
    openssl req -new -key $SCRIPT_DIR/cert/client.key -passin pass:"$PASSWORD" -out $SCRIPT_DIR/cert/client.csr -config $SCRIPT_DIR/openssl-client.cnf
else
    openssl req -new -key $SCRIPT_DIR/cert/client.key -out $SCRIPT_DIR/cert/client.csr -config $SCRIPT_DIR/openssl-client.cnf
fi

# 使用 CA 签发客户端证书：
openssl x509 -req -days 365 -in $SCRIPT_DIR/cert/client.csr -CA $SCRIPT_DIR/cert/ca.crt -CAkey $SCRIPT_DIR/cert/ca.key -out $SCRIPT_DIR/cert/client.crt

# 生成 client.p12 文件（包含私钥和证书）
if [ -n "$PASSWORD" ]; then
    openssl pkcs12 -export -in $SCRIPT_DIR/cert/client.crt -inkey $SCRIPT_DIR/cert/client.key -passin pass:"$PASSWORD" -out $SCRIPT_DIR/cert/client.p12 -passout pass:"$PASSWORD"
else
    openssl pkcs12 -export -in $SCRIPT_DIR/cert/client.crt -inkey $SCRIPT_DIR/cert/client.key -out $SCRIPT_DIR/cert/client.p12 -passout pass:
fi